//
//  WmcEditPhotoToolPreView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/15.
//

import UIKit
import YPBedrock

// MARK: - [WmcEditPhotoPreView]

class WmcEditPhotoPreviewView: WmcBaseView {

    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.isUserInteractionEnabled = true
        let imageTapGesture = UITapGestureRecognizer.YP.Create { [weak self] _ in
            guard let weakSelf = self else { return }
            // 点击图片部分，取消所有标签视图的操作
            weakSelf.cancelAllTagEdit()
        }
        imageView.addGestureRecognizer(imageTapGesture)
        return imageView
    }()

    lazy var scrollView: WmcEditScaleScrollView = {
        let scrollView = WmcEditScaleScrollView()
        scrollView.delegate = self
        scrollView.contentInset = .zero
        scrollView.isMultipleTouchEnabled = true
        scrollView.scrollsToTop = false
//        scrollView.showsHorizontalScrollIndicator = false
//        scrollView.showsVerticalScrollIndicator = true
        scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        scrollView.delaysContentTouches = false
        scrollView.canCancelContentTouches = true
        scrollView.alwaysBounceVertical = false
        if #available(iOS 11.0, *) {
            // 就算超出了安全边距，系统不会对你的scrollView做任何事情，即不作任何调整
            scrollView.contentInsetAdjustmentBehavior = .never
        }
        scrollView.tagTintView = tagTintView
        return scrollView
    }()

    /// 瞄具
    lazy var sightView: UIView = {
        let view = UIView()
        return view
    }()
    
    /// 标签添加视图
    lazy var tagTintView: WmcEditTagTintView = {
        let view = WmcEditTagTintView()
        view.clipsToBounds = true
        view.isUserInteractionEnabled = true
        return view
    }()
    
    /// 展示视图
    var image: UIImage?

    /// 所有标签视图
    var tagViews: [WmcBaseTagView] = []

    /// 编辑标签回调
    var editTagBlock: YPBlock.OneParam<WmcBaseTagView>?

    /// 瞄具中心
    var sightCenter: CGPoint {
        let screenRect = sightView.convert(sightView.bounds, to: imageView)
        return screenRect.yp.center
    }

    func cancelAllTagEdit() {
        tagViews.forEach { tagView in
            tagView.isFirstEdit = false
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        loadImage()
    }

    override func makeUI() {
        backgroundColor = .black
        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.center.size.equalToSuperview()
        }
        scrollView.addSubview(imageView)

        imageView.addSubview(tagTintView)
        tagTintView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        addSubview(sightView)
        sightView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(28)
        }
    }

    /// 添加标签视图
    func addTag(_ view: WmcBaseTagView, isSightCenter: Bool = true, isAutoScale: Bool = true) {
        if isSightCenter {
            view.center = sightCenter
        }
        tagTintView.addSubview(view)
        if isAutoScale {
            let imageViewSize = imageView.frame.size
            let scaleX = UIScreen.main.bounds.width / imageViewSize.width
            let compensationScale = UIScreen.main.bounds.width / (imageView.image?.size.width ?? UIScreen.main.bounds.width)
            let tagScale = scaleX / compensationScale
            view.currentScale = tagScale
            view.transform = CGAffineTransform.YP.CreateScale(tagScale)
        }
        // 移除其他标签的编辑状态
        tagViews.forEach { tagView in
            tagView.isFirstEdit = false
        }
        tagViews.append(view)
        scrollView.tagViews = tagViews
        // 新添加的标签为编辑者
        view.isFirstEdit = true
        // 添加点击手势
        let gesture = UITapGestureRecognizer.YP.Create { [weak self] tap in
            guard let weakSelf = self,
                  let tapView = tap.view as? WmcBaseTagView else { return }
            if tapView.isFirstEdit {
                weakSelf.editTagBlock?(tapView)
            } else {
                // 移除其他标签的编辑状态
                weakSelf.tagViews.forEach { tagView in
                    tagView.isFirstEdit = tagView == tapView
                }
            }
        }
        view.addGestureRecognizer(gesture)
        // 设置手势回调
        view.gestureEndBlock = { [weak self] tagView in
            guard let weakSelf = self else { return }
            if !weakSelf.imageView.bounds.contains(tagView.center) {
                Wmc_SpringAnimation() { [weak self] in
                    guard let weakSelf = self else { return }
                    tagView.center = weakSelf.sightCenter
                } 
            }
        }
    }

    func loadImage() {
        guard let image = image,
              imageView.frame.size == .zero else { return }
        // 加载scroll的contentSize
        imageView.image = image
        imageView.frame = CGRect(origin: .zero, size: image.size)
        imageViewCenter()
        scrollView.setZoomScale(1, animated: false)

        // 缩放
        let minWidthScale = frame.size.width / image.size.width
        let minHeightScale = frame.size.height / image.size.height
        let minZoomScale = min(minWidthScale, minHeightScale)
        scrollView.minimumZoomScale = minZoomScale
        scrollView.maximumZoomScale = 3
        scrollView.setZoomScale(minZoomScale, animated: false)
    }

    func imageViewCenter() {
        let boundSize = scrollView.bounds.size
        var contentFrame = imageView.frame
        if contentFrame.width < boundSize.width {
            contentFrame.origin.x = (boundSize.width - contentFrame.width) / 2
        } else {
            contentFrame.origin.x = 0
        }
        if contentFrame.height < boundSize.height {
            contentFrame.origin.y = (boundSize.height - contentFrame.height) / 2
        } else {
            contentFrame.origin.y = 0
        }
        imageView.frame = contentFrame
    }
}

// MARK: - UIScrollViewDelegate

extension WmcEditPhotoPreviewView: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }

    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        scrollView.setZoomScale(scale, animated: true)
    }

    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        imageViewCenter()
    }
}
